<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)" label-align="top">
        <t-form-item label="编号" name="recordId">
          <t-input v-model="queryParams.recordId" placeholder="请输入编号" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="兑换所用积分" name="redemptionPoints">
          <t-input v-model="queryParams.redemptionPoints" placeholder="请输入兑换所用积分" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="兑换所用货币金额" name="redemptionCurrency">
          <t-input v-model="queryParams.redemptionCurrency" placeholder="请输入兑换所用货币金额" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="兑换日期和时间">
          <t-date-range-picker
            v-model="dateRangeRedemptionDate"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label="兑换状态" name="status">
          <t-select v-model="queryParams.status" placeholder="请选择兑换状态" clearable>
            <t-option
              v-for="dict in status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label-width="0px">
            <t-space align="end" style="height: 64px">
                <t-button theme="primary" @click="handleQuery">
                    <template #icon> <search-icon /></template>
                    搜索
                </t-button>
                <t-button theme="default" @click="resetQuery">
                    <template #icon> <refresh-icon /></template>
                    重置
                </t-button>
            </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="recordId"
        :data="goodsRedemptionRecordsList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xhlj:goodsRedemptionRecords:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xhlj:goodsRedemptionRecords:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xhlj:goodsRedemptionRecords:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xhlj:goodsRedemptionRecords:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>



        <template #wxUser="{ row }">
            <span v-if="row.wxUser && Object.keys(row.wxUser).length > 1">
              {{ row.wxUser[Object.keys(row.wxUser)[1]] }}（编号为{{ row.wxUser[Object.keys(row.wxUser)[0]] }}）
            </span>
        </template>

        <template #goods="{ row }">
            <span v-if="row.goods && Object.keys(row.goods).length > 1">
              {{ row.goods[Object.keys(row.goods)[1]] }}（编号为{{ row.goods[Object.keys(row.goods)[0]] }}）
            </span>
        </template>



        <template #status="{ row }">
            <dict-tag :options="status" :value="row.status" />
        </template>

        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xhlj:goodsRedemptionRecords:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xhlj:goodsRedemptionRecords:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xhlj:goodsRedemptionRecords:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>
    <!-- 添加或修改商品兑换记录对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading">
        <t-form
          ref="goodsRedemptionRecordsRef"
          label-align="top"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >

          <t-form-item label="兑换所用积分" name="redemptionPoints">
            <t-input-number v-model="form.redemptionPoints" placeholder="请输入" />
          </t-form-item>

    <t-form-item label="兑换的商品" name="goods">
        <t-select v-model="form.goodsId" :options="optionsXhljGoods" clearable placeholder="请选择兑换的商品">
            <template #panelTopContent>
                <div style="padding: 6px 6px 0 6px">
                    <t-textarea v-model="searchXhljGoods" placeholder="请输入关键词搜索" @change="onSearchXhljGoods" />
                </div>
            </template>
        </t-select>
    </t-form-item>

          <t-form-item label="兑换所用货币金额" name="redemptionCurrency">
            <t-input-number v-model="form.redemptionCurrency" placeholder="请输入" />
          </t-form-item>

          <t-form-item label="兑换日期和时间" name="redemptionDate">
            <t-date-picker
              v-model="form.redemptionDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择兑换日期和时间"
            />
          </t-form-item>

          <t-form-item label="兑换状态" name="status">
            <t-radio-group v-model="form.status">
              <t-radio
                v-for="dict in status"
                :key="dict.value"
                :value="dict.value"
              >{{dict.label}}</t-radio>
            </t-radio-group>
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 商品兑换记录详情 -->
    <t-dialog
      v-model:visible="openView"
      header="商品兑换记录详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">

        <t-descriptions-item label="编号">{{ form.recordId }}</t-descriptions-item>

        <t-descriptions-item label="兑换所用积分">{{ form.redemptionPoints }}</t-descriptions-item>

        <span v-if="form.wxUser && Object.keys(form.wxUser).length > 1">
              {{ form.wxUser[Object.keys(form.wxUser)[1]] }}（编号为{{ form.wxUser[Object.keys(form.wxUser)[0]] }}）
        </span>

        <span v-if="form.goods && Object.keys(form.goods).length > 1">
              {{ form.goods[Object.keys(form.goods)[1]] }}（编号为{{ form.goods[Object.keys(form.goods)[0]] }}）
        </span>

        <t-descriptions-item label="兑换所用货币金额">{{ form.redemptionCurrency }}</t-descriptions-item>

        <t-descriptions-item label="兑换日期和时间">{{ parseTime(form.redemptionDate) }}</t-descriptions-item>

        <t-descriptions-item label="兑换状态">
          <dict-tag :options="status" :value="form.status" />
        </t-descriptions-item>

      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'GoodsRedemptionRecords',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { SelectProps, TextareaProps, FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, TableSort } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XhljGoodsRedemptionRecordsForm, XhljGoodsRedemptionRecordsQuery, XhljGoodsRedemptionRecordsVo } from '@/api/xhlj/model/goodsRedemptionRecordsModel';
import { listGoodsRedemptionRecords, getGoodsRedemptionRecords, delGoodsRedemptionRecords, addGoodsRedemptionRecords, updateGoodsRedemptionRecords } from '@/api/xhlj/goodsRedemptionRecords';
import type { XhljGoodsQuery } from '@/api/xhlj/model/goods';
import { listGoods } from '@/api/xhlj/goods';


const { proxy } = getCurrentInstance();
const { status } = proxy.useDict('status');

const openView = ref(false);
const openViewLoading = ref(false);
const goodsRedemptionRecordsRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const goodsRedemptionRecordsList = ref<XhljGoodsRedemptionRecordsVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();



const queryParamsXhljGoods = ref<XhljGoodsQuery>({
    pageNum: 1,
    pageSize: 10000,
});
const listXhljGoods = [];
const optionsXhljGoods = ref<SelectProps['options']>(listXhljGoods);
const searchXhljGoods = ref('');
const onSearchXhljGoods: TextareaProps['onChange'] = () => {
    optionsXhljGoods.value = listXhljGoods.filter((item) => item.label.indexOf(searchXhljGoods.value) !== -1);
};
/** 查询兑换的商品列表 */
function getGoodsList() {
    listGoods(queryParamsXhljGoods.value)
        .then((response) => {
            response.rows.forEach((item) => {
                const option: SelectProps = {
                    label: item[Object.keys(item)[1]],
                    value: item[Object.keys(item)[0]],
                };
                listXhljGoods.push(option)
            });
            console.log("XhljGoods", response.rows)
            console.log("listXhljGoods", listXhljGoods)
        })
}


const dateRangeRedemptionDate = ref([]);



// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `编号`, colKey: 'recordId', align: 'center', ellipsis: true },
  { title: `兑换所用积分`, colKey: 'redemptionPoints', align: 'center' },
  { title: `微信用户`, colKey: 'wxUser', align: 'center', minWidth: 100, ellipsis: true },
  { title: `兑换的商品`, colKey: 'goods', align: 'center', minWidth: 100, ellipsis: true },
  { title: `兑换所用货币金额`, colKey: 'redemptionCurrency', align: 'center' },
  { title: `兑换日期和时间`, colKey: 'redemptionDate', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `兑换状态`, colKey: 'status', align: 'center' },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120 },
]);
// 提交表单对象
const form = ref<XhljGoodsRedemptionRecordsVo & XhljGoodsRedemptionRecordsForm>({});
// 查询对象
const queryParams = ref<XhljGoodsRedemptionRecordsQuery>({
  pageNum: 1,
  pageSize: 10,
  recordId: undefined,
  redemptionPoints: undefined,
  redemptionCurrency: undefined,
  status: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询商品兑换记录列表 */
function getList() {
  loading.value = true;
  proxy.addDateRange(queryParams.value, dateRangeRedemptionDate.value, 'RedemptionDate');
  listGoodsRedemptionRecords(queryParams.value)
    .then((response) => {
      goodsRedemptionRecordsList.value = response.rows;
      total.value = response.total;
      console.log("GoodsRedemptionRecords", response.rows)
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('goodsRedemptionRecordsRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeRedemptionDate.value = [];
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加商品兑换记录';
}

/** 详情按钮操作 */
function handleDetail(row: XhljGoodsRedemptionRecordsVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const recordId = row.recordId;
  getGoodsRedemptionRecords(recordId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XhljGoodsRedemptionRecordsVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改商品兑换记录';
  const recordId = row?.recordId || ids.value.at(0);
  getGoodsRedemptionRecords(recordId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  goodsRedemptionRecordsRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.recordId) {
      updateGoodsRedemptionRecords(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addGoodsRedemptionRecords(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XhljGoodsRedemptionRecordsVo) {
  const recordIds = row?.recordId || ids.value;
  proxy.$modal.confirm(`是否确认删除商品兑换记录编号为${recordIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delGoodsRedemptionRecords(recordIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, recordIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.addDateRange(queryParams.value, dateRangeRedemptionDate.value, 'RedemptionDate');
  proxy.download(
    'xhlj/goodsRedemptionRecords/export',
    {
      ...queryParams.value,
    },
    `goodsRedemptionRecords_${new Date().getTime()}.xlsx`,
  );
}

getList();
getGoodsList();
</script>
